<?php
namespace App\Http\Controllers\Agent;
use App\Http\Controllers\AgentController;
use App\Models\Level as TLevel;
use Illuminate\Http\Request;
use App\Models\Agent;
use App\Models\Mem;
use App\Models\Set;
use App\Models\LevelOrder;

class Level extends AgentController{
    public function index(Request $req){
        if ($req->post('op') == 'bind'){
            $mobile = $req->post('mobile','');
            if (empty($mobile)) wxresp(0,'请输入手机号码');
            if (strlen($mobile) != 11) wxresp(0,'请输入正确号码');
            $agent = Agent::where('mobile',$mobile)->first();
            if ($agent) wxresp(0,'该手机号码已绑定');
            Mem::where('id',$req->mem->id)->update(array('mobile'=>$mobile));
            if ($req->agent) Agent::where('id',$req->agent->id)->update(array('mobile'=>$mobile));
            wxresp(1);
        }
        $list = TLevel::select('level','title','rule','uprice')->get();
        $dprice = 0;
        if ($req->agent){
            $dprice = TLevel::where('level',$req->agent->level)->value('uprice');
            if (!$req->mem->mobile && $req->agent->mobile) {
                Mem::where('id',$req->mem->id)->update(array('mobile'=>$req->agent->mobile));
                $req->mem->mobile = $req->agent->mobile;
            }
        }
        foreach ($list as &$v) {
            if ($v->uprice > 0) $v->uprice = round($v->uprice - $dprice,2);
        }
        wxresp(1,['list'=>$list,'level'=>$req->agent->level??-1,'needmobile'=>empty($req->mem->mobile) ?  1 : 0]);
    }
    
    public function pay(Request $req){
        $level = $req->post('level');
        $l = TLevel::where('level',$level)->first();
        if ($req->agent){
            if ($l->level < $req->agent->level) wxresp(0,'无需升级');
            $l['uprice'] -= TLevel::where('level',$req->agent->level)->value('uprice');
        }
        $order = array(
                'aid'=>$req->agent->id ?? 0,
                'mid'=>$req->mem->id,
                'ordersn'=>'UP'.date('YmdHis').random(6,1),
                'price'=>$l['uprice'],
                'level'=>$l->level,
                'reback'=>$l->bprice,
                'createtime'=>time()
        );
        $set = Set::getSet('wxpay');
        $pay = new \WxPay($set);
        $params = array(
                'openid'=>$req->mem->openid,
                'body'=>'升级等级',
                'price'=>$order['price'],
                'orderno'=>$order['ordersn'],
                'notify_url'=>'https://'.$req->host()."/notify/".$order['ordersn']
        );
        $res = $pay->wxappPay($params);
        if($res['code'] == 0) wxresp(0,$res['msg']);
        $orderid = LevelOrder::insertGetId($order);
        $preresult = $res['paydata'];
        $preresult['orderid'] = $orderid;
        wxresp(1,array('data'=>$preresult));
    }
}